"""
重写threading.Thread类，以获取每个线程的结果
"""
import threading

# 多线程如何返回值
class MyThread(threading.Thread):
    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result  # 如果子线程不使用join方法，此处可能会报没有self.result的错误
        except Exception:
            return None


def add(a, b):
    return a + b


if __name__ == '__main__':
    threads = []

    t1 = MyThread(add, args=(
        1,
        2,
    ))
    threads.append(t1)
    t2 = MyThread(add, args=(
        3,
        4,
    ))
    threads.append(t2)

    for t in threads:
        t.setDaemon(True)
        t.start()
    print("t1 : a+b=%d !" % (t1.get_result()))
    print("t2 : a+b=%d !" % (t2.get_result()))
